// pages/page/home/home.js
const app = getApp();
var request_api = require('../../../utils/require_api.js');
const config = require("../../../config.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    phone: '', //电话号码
    modalName: null, //底部弹出框是否显示
    all_company: [], //拥有的公司
    current_company: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options, "我是home的onLoad")
  },
  //跳转到资源中心
  resource_center(){
    if (wx.getStorageSync("phone") == '') {
      wx.showToast({
        title: '请完成手机绑定功能',
      })
      return;
    }else{
      wx.reLaunch({
        url: '/pages/page/sheping/resource_index/resource_index'
      })
    }
    
  },
  //资源配置   直接跳转到首页
  resource_allocation(e) {
    if (wx.getStorageSync("NICK_NAME") == '') {
      wx.showToast({
        title: '请先完成登陆哦',
      })
      return;
    }
    if (e.currentTarget.dataset.ziyuan == 1) {
       wx.navigateTo({
        url: '/pages/index/index?tuiguang=' + 1
      })
    } else if (e.currentTarget.dataset.ziyuan == 2) {
      wx.reLaunch({
        url: '/pages/index/index?tuiguang=' + 2
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      show_company: wx.getStorageSync("show_company"),
      entityName: wx.getStorageSync("entityName"),
      company_name: wx.getStorageSync("company_name"),
      userimg: wx.getStorageSync("USER_IMAGE"),
      username: wx.getStorageSync("NICK_NAME"),
      // entityName: wx.getStorageSync("entityName"),
      phone: wx.getStorageSync("phone"),
    })
  },

  //手机绑定
  phone_bind(phone) {
    if (wx.getStorageSync("NICK_NAME") == '') {
      wx.showToast({
        title: '请先完成登陆哦',
      })
      return;
    }
    let phone_bind = '';
    if (wx.getStorageSync("phone") == '') {
      phone_bind = '手机绑定';
    } else {
      phone_bind = '手机修改';
    }
    wx.navigateTo({
      url: `/pages/page/PhoneVerification/PhoneVerification?pagename=${phone_bind}`,
    })
  },
  //切换公司
  change_company() {
    var that = this;
    request_api.request({
        "cmd": "weixin|switch_company",
        "paras": []
      }, //需要传的 data
      function(res) {
        console.log(res, "this is home.js 73 change_company")
        let a = res.data.result;
        for (let i = 0; i < a.length; i++) {
          if (a[i].company_key == wx.getStorageSync("company_key")) {
            a[i].checked = true;
            wx.setStorageSync("show_company", a[i].company_name);
            wx.setStorageSync("entityName", a[i].entityName);
          } else {
            a[i].checked = false;
          }
        }
        that.setData({
          all_company: a,
          show_company: wx.getStorageSync("show_company"),
          entityName: wx.getStorageSync('entityName'),
          modalName: 'bottomModal'
        })
      },
      function() {
        console.log("错误");
      },
    )
  },
  //隐藏切换公司的dialog
  hideModal() {
    this.setData({
      modalName: null
    })
  },
  radioChange(e) {
    this.data.current_company = e.detail.value;
  },
  // 确定单选框
  queryModel() {
    let show_company = '';
    let entityName = '';
    let ekey = '';
    if (this.data.current_company) {
      console.log(this.data.current_company, "this is home.js 73 queryModel")
      wx.setStorageSync("company_key", this.data.current_company);
      for (let i = 0; i < this.data.all_company.length; i++) {
        if (this.data.all_company[i].company_key == this.data.current_company) {
          show_company = this.data.all_company[i].company_name
          entityName = this.data.all_company[i].entityName
          ekey = this.data.all_company[i].ekey;
        }
      }
      wx.setStorageSync("show_company", show_company);
      wx.setStorageSync("entityName", entityName);
      wx.setStorageSync("ekey", ekey);
      this.setData({
        modalName: null,
        show_company: wx.getStorageSync("show_company"),
        entityName: wx.getStorageSync("entityName")
      })

      request_api.request({
          "cmd": "weixin|set_default_company",
          "paras": [{
              "name": "current_company_key",
              "value": wx.getStorageSync("company_key")
            },
            {
              "name": "ekey",
              "value": ekey
            },
            {
              "name": "wx_openid",
              "value": wx.getStorageSync("openid")
            }
          ]
        }, //需要传的 data
        function(res) {
          console.log(res, "this is home.js 137 设置默认公司");
          wx.showToast({
            title: '切换成功',
          })
        }
      )
    } else {
      this.setData({
        modalName: null
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      modalName: null
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  bindGetUserInfo: function(e) { //点击授权登录  把用户基本信息保存到本地存储中，斌且调用登录方法获取openid
    var n = this;
    wx.getUserInfo({
      success: function(t) {
        app.globalData.userInfo = t.userInfo,
          wx.setStorageSync("NICK_NAME", t.userInfo.nickName),
          wx.setStorageSync("USER_IMAGE", t.userInfo.avatarUrl),
          wx.setStorageSync("PROVINCE", t.userInfo.province),
          wx.setStorageSync("CITY", t.userInfo.city),
          n.login().then(function() {
            console.log("成功登陆");
          });
      },
      fail: function(t) {
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击了“返回授权”')
            }
          }
        })
      }
    });
  },

  login: function() { //授权登录获取openid方法
    var t = this;

    return wx.showLoading({
      title: "授权登录中"
    }), 
    new Promise(function(o, e) {
      wx.login({
        success: function(e) {
          e.code ? (
            wx.getUserInfo({
              success: function(datas) {
                request_api.send(config.uri + '/api/wx/Login4WX', { //获取openid
                    "code": e.code,
                    'openid': '',
                    'platform': config.wxcode,
                    'wechat_name':datas.userInfo.nickName||''
                  }, //需要传的 data
                  function(res) {
                    if (res.data.errcode == 0) {
                      wx.setStorageSync("openid", res.data.openid); //把获取到的数据保存到本地缓存中，便于其他页面使用
                      wx.setStorageSync("company_key", res.data.company_key); //公司key
                      wx.setStorageSync("show_company", res.data.company_name); //公司名字
                      wx.setStorageSync("entityName", res.data.entityName); //店铺名字
                      wx.setStorageSync("entity_code", res.data.entity_code); //获取店铺编码
                      wx.setStorageSync("name", res.data.name); //获取用户名字
                      wx.setStorageSync("phone", res.data.phone); //获取电话号码
                      wx.setStorageSync("token", res.data.token); //获取token
                      wx.setStorageSync("user_key", res.data.user_key); //用户的key
                      wx.setStorageSync("ekey", res.data.ekey); //店铺的ekey
                      t.get_wx_manager(res.data.openid).then(jj => {
                        wx.redirectTo({
                          url: '../../index/index',
                        })
                      });
                    } else {
                      wx.setStorageSync("openid", res.data.openid); //把获取到的数据保存到本地缓存中，便于其他页面使用
                      wx.showToast({
                        title: '请先完成手机绑定！',
                        icon: 'none'
                      })
                      setTimeout(function() {
                        wx.redirectTo({
                          url: '../home/home',
                        })
                      }, 1000)
                    }
                  },
                  function(res) {
                    wx.showToast({
                      title: '登录错误！',
                    })
                  },
                )
              }
            })
          ) : (t.loginFailed());
        }
      });
    });
  },
  loginFailed: function() {
    wx.showModal({
      title: "提示",
      content: "登录失败!",
      showCancel: !1
    }), wx.hideLoading();
  },
  //获取用户是否是为后台管理员
  get_wx_manager(openid) {
    var p = new Promise(function(resolve, reject) {
      resolve("调用成功");
      request_api.request({
          "cmd": "weixin_api|get_wx_manager",
          "paras": [{
            name: "openid",
            value: openid
          }]
        }, //需要传的 data
        function(res) {
          console.log(res, "this is look people is manager  home.js 303?");
          if (res.data.errid == 0) {
            if (res.data.result.length != 0) {
              wx.setStorageSync('ismanager', 1);
            } else {
              wx.setStorageSync('ismanager', 0);
            }
          }
        },
        function() {
          console.log("错误");
        },
      )
    })
    return p;
  },

})